import router from '@/router';
import { USER } from './const/sessionStoreKeys';

const whiteList = ['/login'];

// 全局路由前置钩子
router.beforeEach(async (to, from, next) => {
  const localUserData = sessionStorage.getItem(USER);
  const hasToken = JSON.parse(localUserData)?.token;

  if (hasToken) {
    const [LOGIN_PATH] = whiteList;
    if (to.path === LOGIN_PATH) {
      next({ path: '/' });
    } else {
      next();
    }
  } else if (whiteList.indexOf(to.path) !== -1) {
    next();
  } else {
    // other pages that do not have permission to access are redirected to the login page.
    next(`/login?redirect=${to.path}`);
  }
});

export default router;
